package com.springboot2.service.Impl;

import com.springboot2.entity.Org;
import com.springboot2.entity.Resource;
import com.springboot2.mapper.ResourceMapper;
import com.springboot2.service.ResourceService;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class ResourceServiceImpl implements ResourceService {

    @javax.annotation.Resource
    private ResourceMapper resourceMapper;

    @Override
    public void add(Resource resource) {
        resourceMapper.add(resource);
    }

    @Override
    public void del(int id) {
        resourceMapper.del(id);
    }

    @Override
    public void update(Resource resource) {
        resourceMapper.update(resource);
    }

    @Override
    public Resource findById(int id) {
        return resourceMapper.findById(id);
    }

    @Override
    public List<Resource> findByPage(Integer pageNo, Integer pageSize) {
        Map<String,Integer> map = new HashMap<>();
        map.put("pageNo",(pageNo-1)*pageSize);
        map.put("pageSize",pageSize);

        List<Resource> list = resourceMapper.findByPage(map);

        return childrenTree(null,list);
    }


    @Override
    public int count() {
        return resourceMapper.count();
    }

    @Override
    public List<Resource> findByPageParams(Integer pageNo, Integer pageSize, String name) {
        Map<String,Object> map = new HashMap<>();
        map.put("pageNo",(pageNo-1)*pageSize);
        map.put("pageSize",pageSize);
        map.put("name",name+"%");

        List<Resource> list = resourceMapper.findByPageParams(map);

        return childrenTree(null,list);
    }

    @Override
    public int countParams() {
        return resourceMapper.countParams();
    }

    @Override
    public List<Resource> findList() {
        List<Resource> list = resourceMapper.findList();
        return childrenTree(null,list);
    }

    @Override
    public List<Integer> findAllId() {
        return resourceMapper.findId();
    }

    //递归生成 树状结构
    private List<Resource> childrenTree(Integer pid, List<Resource> allData){
        List<Resource> list = new ArrayList<>();
        for (Resource resource : allData) {
            if(Objects.equals(resource.getPid(),pid)){
                list.add(resource);
                List<Resource> childrenTree = childrenTree(resource.getId(),allData);
                resource.setChildren(childrenTree);
            }
        }
        return list;
    }
}
